//
//  CustomerServiceViewController.m
//  mdc
//
//  Created by 123456 on 16/10/11.
//  Copyright © 2016年 YTYangK. All rights reserved.
//

#import "CustomerServiceViewController.h"
#import "CustomCell.h"
#import "ChatModel.h"

@interface CustomerServiceViewController ()<UITextViewDelegate,UITableViewDelegate,UITableViewDataSource,UIScrollViewDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>
{
    int i;//记录当前textView坐标
    UIView *v;
}


@property (weak, nonatomic) IBOutlet UITableView *CustomerServiceTableview;
@property (weak, nonatomic) IBOutlet UIView *Tview;
@property (weak, nonatomic) IBOutlet UITextView *TextView;

@property (weak, nonatomic) IBOutlet UIButton *PictureButton;

//数据源
@property (nonatomic,strong)NSMutableArray *dataArray;

@property (nonatomic,strong)NSArray *arr;

@end

@implementation CustomerServiceViewController

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];

}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self Interface];
    

//    [self.CustomerServiceTableview registerNib:[UINib nibWithNibName:@"ChatTableViewCell" bundle:nil] forCellReuseIdentifier:@"cell"];
//       [self.CustomerServiceTableview registerNib:[UINib nibWithNibName:@"ChatTableViewCell1" bundle:nil] forCellReuseIdentifier:@"cell1"];


    
}



-(void)Interface{
    
    self.title = @"客服";
    
    self.view.backgroundColor =  RGB(33, 38, 44, 1);
    self.CustomerServiceTableview.backgroundColor =RGB(33, 38, 44, 1);
    self.TextView.delegate = self;
    self.Tview.backgroundColor=UIColorFromRGB(0x2f4050);
    self.TextView.backgroundColor =UIColorFromRGB(0x2f4050);
    [self.PictureButton setBackgroundColor:UIColorFromRGB(0x528bcb)];
    self.TextView.tintColor = [UIColor whiteColor];
    self.CustomerServiceTableview.separatorStyle = UITableViewCellSelectionStyleNone;
    
    self.TextView.keyboardType
    = UIKeyboardTypeDefault;//键盘类型
    self.TextView.returnKeyType
    = UIReturnKeySend;//返回键的类型
    
    
    //点击tableview收键盘手势
    UITapGestureRecognizer *tableViewGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(commentTableViewTouchInSide)];
    tableViewGesture.numberOfTapsRequired = 1;
    tableViewGesture.cancelsTouchesInView = NO;
    [self.CustomerServiceTableview addGestureRecognizer:tableViewGesture];
    
   
    
    
}

//点击tableview收键盘响应方法
- (void)commentTableViewTouchInSide{
    [self.TextView resignFirstResponder];
}


//开始编辑
-(BOOL)textViewShouldBeginEditing:(UITextView *)textView
{
    
    textView.text = @"";
    //开始编辑时添加监听键盘
    [self registerForKeyboardNotifications];
    
    return YES;
}

//监听键盘
- (void)registerForKeyboardNotifications
{
    //使用NSNotificationCenter 鍵盤出現時
    [[NSNotificationCenter defaultCenter] addObserver:self
     
                                             selector:@selector(keyboardWasShown:)
     
                                                 name:UIKeyboardWillShowNotification object:nil];
    
    //使用NSNotificationCenter 鍵盤隐藏時
    [[NSNotificationCenter defaultCenter] addObserver:self
     
                                             selector:@selector(keyboardWillBeHidden:)
     
                                                 name:UIKeyboardWillHideNotification object:nil];
    
    
        i = self.TextView.frame.origin.y;
    
}

//键盘激活时，textview跟着偏移
- (void)keyboardWasShown:(NSNotification*)aNotification
{
    
    NSDictionary *userInfo = [aNotification userInfo];
    NSValue *aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardRect = [aValue CGRectValue];
    int height = keyboardRect.size.height;
    
    [UIView animateWithDuration:1 animations:^{
            self.TextViewBottom.constant = height-49;
            CGRect btnFrame = self.Tview.frame;
            btnFrame.origin.y -= height-49;
            self.Tview.frame = btnFrame;
        
    }];
//    [self.CustomerServiceTableview reloadData];
//
//    //延迟0.5秒滚动偏移
//    double delayInSeconds = 0.1;
//    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
//    dispatch_after(popTime, dispatch_get_main_queue(), ^(void) {
//        [self refreshUI];
//        
//    });

}

//收键盘时，textview跟着偏移
- (void)keyboardWillBeHidden:(NSNotification*)aNotification
{
    
    [UIView animateWithDuration:1 animations:^{
        self.TextViewBottom.constant = 0;
        CGRect btnFrame = self.Tview.frame;
        btnFrame.origin.y += i;
        self.Tview.frame = btnFrame;
        
    }];
        [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
        [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];

}


//关闭键盘(TextView) 换行时。隐藏键盘
-(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    if ([text isEqualToString:@"\n"]) {
        [textView resignFirstResponder];
        
        return NO;
    }
    return YES;
}

//结束编辑
-(void)textViewDidEndEditing:(UITextView *)textView
{
    
    if (![textView.text isEqualToString:@""]) {

        ChatModel *model = [[ChatModel alloc]init];
        model.content = self.TextView.text;
        model.type = @"me";
        //加入数据源
        [self.dataArray addObject:model];
        //刷表
        [self.CustomerServiceTableview reloadData];
        
        
        //延迟0.5秒滚动偏移
        double delayInSeconds = 0.1;
        dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
        dispatch_after(popTime, dispatch_get_main_queue(), ^(void) {
            [self refreshUI];
        });

    }
    
    textView.text = @"请输入您的问题...";
}




#pragma mark -  TableView DataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView*)tableView {
    return 1;
}


-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{

    return self.dataArray.count;
    
}


- (UITableViewCell*)tableView:(UITableView*)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath {
    
    CustomCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (cell == nil)
    {
        cell = [[CustomCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
    }
    
    ChatModel *model = _dataArray[indexPath.row];
    cell.backgroundColor =  RGB(33, 38, 44, 1);
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    cell.model = model;
    
    NSLog(@"获取当前模型数据 ====  %@",model);
    return cell;
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{

    ChatModel *model = _dataArray[indexPath.row];
    if (model.typeimage !=nil) {
        return model.contentSize.height+190;
    }
    
    return model.contentSize.height+100;
    
}


- (void)refreshUI
{
    if (self.dataArray.count != 0) {
        //让表格滚动最后一行
        [self.CustomerServiceTableview scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:self.dataArray.count-1  inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:YES];
    }

}


- (NSMutableArray *)dataArray
{
    if (_dataArray == nil )
    {
        _dataArray = [[NSMutableArray alloc]init];
    }
    return _dataArray;
}

//相册
- (IBAction)imagebutton:(UIButton *)sender {
    
    UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
    imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    imagePicker.delegate = self;
    [self  presentViewController:imagePicker animated:YES completion:^{
    }];
}

//点击相册中的图片 货照相机照完后点击use  后触发的方法
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    
    ChatModel *model = [[ChatModel alloc]init];
    model.type = @"me";
    model.typeimage = @"me";
  model.image=UIImageJPEGRepresentation(info[@"UIImagePickerControllerOriginalImage"],1.0);
    [self.dataArray addObject:model];
    
    [self.CustomerServiceTableview reloadData];

    //延迟0.5秒滚动偏移
    double delayInSeconds = 0.1;
    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
    dispatch_after(popTime, dispatch_get_main_queue(), ^(void) {
        [self refreshUI];
    });

    [self dismissViewControllerAnimated:YES completion:nil];

}

//点击cancel 调用的方法
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [self dismissViewControllerAnimated:YES completion:nil];

}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
